package com.dadovicn.auth;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 基础用户信息类
 * @author dadovicn
 * @date   2018/8/31
 */
@Entity
@Data
@Table(name = "SYS_USER")
public class SysUser implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence")
    @SequenceGenerator(name = "sequence", sequenceName="SEQ_SYS_USER", allocationSize=1)
    private long userId;

    @Column(name= "user_name")
    private String userName;

    @Column(name= "mobile")
    private String mobile;

    @Column(name= "email")
    private String email;

    @Column(name= "real_name")
    private String realName;

    @Column(name= "group_id")
    private Long groupId;

    @Column(name= "create_time")
    private Timestamp createTime;

    @Column(name= "update_time")
    private Timestamp updateTime;

    @Column(name= "status")
    private boolean status;

    @Column(name = "avatar_url")
    private String avatarUrl;

    @Column(name = "gender")
    private char gender;

    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "local_auth_id")
    private SysUserLocalAuth sysUserLocalAuth;

    @ManyToMany(cascade = {CascadeType.MERGE})
    @JoinTable(
            name="sys_user_role",
            joinColumns=@JoinColumn(name="user_id"),
            inverseJoinColumns=@JoinColumn(name="role_id"))
    private List<SysRole> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> auths = new ArrayList<>();
        List<SysRole> roles = this.getRoles();
        for (SysRole role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return auths;
    }

    @Override
    public String getPassword() {
        return sysUserLocalAuth.getPassword();
    }

    @Override
    public String getUsername() {
        return this.userName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}